#!/bin/sh

shim_signed_url="http://archive.ubuntu.com/ubuntu/pool/main/s/shim-signed/shim-signed_1.34.9+13-0ubuntu2_amd64.deb"
shim_url="http://archive.ubuntu.com/ubuntu/pool/main/s/shim/shim_13-0ubuntu2_amd64.deb"
shim_blacklist_md5="f7a57b08bc7c1c85417ae4cea582d1d4"

if [ ! -e /usr/lib/grub/i386-pc/moddep.lst ]; then
	echo "Installing grub-pc-bin"
	sudo apt-get install grub-pc-bin #TBD do not assume apt
fi
if [ ! -e /usr/lib/grub/x86_64-efi/moddep.lst ]; then
	echo "Installing grub-efi-amd64-bin"
	sudo apt-get install grub-efi-amd64-bin #TBD do not assume apt
fi
if [ ! -e /usr/lib/grub/i386-efi/moddep.lst ]; then
	echo "Installing grub-efi-ia32-bin"
	sudo apt-get install grub-efi-ia32-bin #TBD do not assume apt
fi
if [ ! -e /usr/lib/shim/shim.efi.signed ] && [ ! -e /usr/lib/shim/shimx64.efi.signed ]; then
	echo "Installing shim-signed..."
	sudo apt-get install shim-signed #TBD do not assume apt
fi
if [ -e /usr/lib/shim/shimx64.efi.signed ] &&
   [ "$(md5sum /usr/lib/shim/shimx64.efi.signed | cut -d ' ' -f 1)" = "$shim_blacklist_md5" ] && 
   ([ ! -e shim/shimx64.efi.signed ] || [ ! -e shim/mmx64.efi ]); then
	echo "Installed shim is blacklisted, downloading new version of shim"
	mkdir -p shim
	wget "$shim_signed_url" -P /tmp -O "/tmp/shim-signed.deb"
	dpkg -x /tmp/shim-signed.deb /tmp/shim
	wget "$shim_url" -P /tmp -O "/tmp/shim.deb"
	ar p /tmp/shim.deb data.tar.xz | tar xvfJ - -C /tmp/shim
	cp /tmp/shim/usr/lib/shim/shimx64.efi.signed shim/.
	cp /tmp/shim/usr/lib/shim/mmx64.efi shim/.
fi
if [ ! -e /usr/bin/sbsign ]; then
	echo "Installing sbsigntool..."
	sudo apt-get install sbsigntool #TBD do not assume apt
fi
if [ ! -e /usr/bin/openssl ];then
	echo "Installing openssl..."
	sudo apt-get install openssl #TBD do not assume apt
fi
if [ ! -e .key ];then
	echo "generating new Secure Boot key..."
	mkdir .key
        openssl req -new -x509 -newkey rsa:2048 -keyout .key/$(whoami)_wubi.key \
	-out  .key/$(whoami)_wubi.crt -nodes -days 3650 -subj "/CN="$(whoami)" Wubi/"
	openssl x509 -in  .key/$(whoami)_wubi.crt -out  .key/$(whoami)_wubi.cer -outform DER
fi
if [ ! -e data/custom-installation/packages/lupin-support ]; then
	echo "Downloading lupin-support packages"
	mkdir -p data/custom-installation/packages/lupin-support
	cd data/custom-installation/packages/lupin-support
	apt-get download lupin-support:i386 #TBD do not assume apt
	apt-get download lupin-support:amd64 #TBD do not assume apt
	cd ../../../..
fi
